package com.kuqi.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.kuqi.config.Result;
import com.kuqi.domain.User;
import com.kuqi.domain.UserAvatar;
import com.kuqi.service.FilesService;
import com.kuqi.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author:kuqi
 * @createTime:2021/11/13 15:05
 * @description:
 */
@RestController
@RequestMapping("/files")
public class FilesController {

    @Autowired
    private FilesService filesService;

    @Value("${server.port}")
    private String port;

    @Value("${file.ip}")
    private String ip;

    /**
     * 文件上传接口
     *
     * @return
     */
    @PostMapping("/upload")
    private Result<?> upload(MultipartFile file, HttpServletRequest request) throws IOException {

        String originalFilename = file.getOriginalFilename(); //获取文件名
        String uuid = IdUtil.simpleUUID(); //生成唯一标识，引入huTool工具依赖包
        String fileName = uuid + "_" + originalFilename;
        InputStream is = file.getInputStream(); //获取输入流
        FileOutputStream fos = new FileOutputStream("E:\\ideaWorkSpace\\springboot-vue\\springboot-vue-pro\\backend\\src\\main\\resources\\userUpdateFiles\\" + fileName);

        byte[] bytes = new byte[1024];
        int len = 0;

        while ((len = is.read(bytes)) != -1) {
            fos.write(bytes, 0, len);
        }
        fos.close();
        is.close();

        String avatar = ip + ":" + port + "/files/" + uuid;
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        Integer userid = user.getId();
        UserAvatar userAvatar = new UserAvatar();
        userAvatar.setUserid(userid);
        userAvatar.setAvatar(avatar);
        filesService.saveAvatar(userAvatar);

        return Result.success(ip + ":" + port + "/files/" + uuid);
    }


    @GetMapping("/getAvatar")
    private Result<?> getAvatar(@RequestParam(value = "id") Integer id) {
        String imageUrl = null;
        Result<String> avatarMessage = null;
        try {
            UserAvatar avatar = filesService.getAvatar(id);
            imageUrl = avatar.getAvatar();
        } catch (Exception e) {
            avatarMessage = Result.success("暂未设置头像");
        } finally {
            avatarMessage = Result.success(imageUrl);
        }
        return avatarMessage;
    }


    @GetMapping("/{flag}")
    private void getFiles(@PathVariable String flag, HttpServletResponse response) {
        //创建一个输出流对象
        OutputStream os;
        //指定到文件上传的根路径
        String basePath = System.getProperty("user.dir") + "/backend/src/main/resources/userUpdateFiles/";
        //获取所有文件名称
        List<String> fileNames = FileUtil.listFileNames(basePath);
        //匹配跟参数一致的文件
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");

        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                //通过文件的路径读取文件字节流
                byte[] bytes = FileUtil.readBytes(basePath + fileName);
                //通过输出流返回文件
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
                System.out.println("下载成功");
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }
}
